<?php

//Yii::import('llamadas.models._base.BaseReporte');
//class LlamadaReporte extends BaseReporte {
class VentaReporte extends CFormModel {

    //Atributos
    public $fechas;

    //   public static $tiposLlamadas = array(
    //       'Recibida','Atendida','Abandonada'
    //   );

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            array('fechas', 'required'), //pendiente
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'fechas' => Yii::t('app', 'fechas'),
        );
    }

    public function generatePieReport() {

//        $inicio = DateTime::createFromFormat('d/m/Y', $inicio);
//        $fin = DateTime::createFromFormat('d/m/Y', $fin)->modify('+1 day');
        $report = array();
        $report['title']['text'] = 'Pedidos';
        $report['credits']['enabled'] = false;
//        $report['chart']['height'] = '400';
//          $report['chart']['type'] = 'pie';
//             $report['chart']['margin'] = '85';
//        $report['chart']['type'] = 'pie';

        $report['chart'] = array(
            'type' => 'pie',
            'options3d' => array(
                'enabled' => true,
                'alpha' => 45,
                'beta' => 0,
        ));
        $report['tooltip']['pointFormat'] = '{series.name}: <b>{point.percentage:.1f}%</b>';
        $report['plotOptions'] = array(
            'pie' => array(
                'allowPointSelect' => true,
                'cursor' => 'pointer',
                'depth' => 35,
                'dataLabels' => array(
                    'enabled' => true,
                    'format' => '{point.name}'
                ),
//                'showInLegend' => true,
//                'tooltip' => array(
//                    'pointFormat' => '{series.name}: <b>{point.percentage:.1f}%</b>'
//                ),
            )
        );
        $report['series'] = array();
        $consulta = Yii::app()->db->createCommand()
                ->select('count(p.id) count , p.estado  nombre')
                ->from('pedido p')
                ->group('p.estado');


        $options = $consulta->queryAll();
        $series = array(
            'type' => 'pie',
            'name' => 'Cantidad',
//            'sliced'=> true,
//            'selected'=> true,
            'data' => array()
        );
        foreach ($options as $option) {
            $series['data'][] = array($option['nombre'], (int) $option['count']);
        }
        $report['series'][] = $series;
//        var_dump($report['series'][0]['data']);
//        var_dump($report['series']);
        return $report;
    }

    public function generateColumnReport($inicio, $fin) {
        $inicio = DateTime::createFromFormat('d/m/Y', $inicio)->setTime(0, 0, 0);
        $fin = DateTime::createFromFormat('d/m/Y', $fin)->setTime(0, 0, 0);
        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
        $dias = 0;
        $report = array();
        $report['title']['text'] = 'Ventas';
        $report['credits']['enabled'] = false;
        $report['chart']['height'] = '400';
//          $report['chart']['type'] = 'column';
//		   $report['chart']['margin'] = '100';
//
//		 $report['chart']['options3d'] = array(
//                'enabled'=> true,
//                'alpha'=> 5,
//                'beta'=> 25,
//               
//            );
//			$report['plotOptions']= array('column'=>array(
//                'depth'=> 25
//            ));
        $report['subtitle']['text'] = ' Desde: ' . $inicio->format('d-m-Y') . '  Hasta: ' . $fin->format('d-m-Y');
        $report['xAxis']['labels'] = array("rotation" => -45);
        $report['yAxis']['min'] = 0;
        $report['yAxis']['title']['text'] = "Número de ventas";
        $report['yAxis']['allowDecimals'] = false;
        $report['xAxis']['categories'] = array();
        $report['series'] = array();
        $motivos = Empleado::model()->findall();
        //        array_push($motivos);
        foreach ($period as $date) {
            $dias++;
        }
        switch (true) {
            //horas
            case ($dias == 0):
                $interval = DateInterval::createFromDateString('1 hour');
                $fin->add(new DateInterval('PT23H59M59S'));
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                foreach ($motivos as $motivo) {
                    $data = array();
                    foreach ($period as $date) {

                        $inicio = $date->format('Y-m-d H:i:s');
                        $categoria = $date->format('H:i');
                        $date->add(new DateInterval('PT59M59S'));
                        $fin = $date->format('Y-m-d H:i:s');
                        $report['xAxis']['categories'][] = $categoria;
                        array_push($data, $this->consulta($motivo, $inicio, $fin));
                    }

                    array_push($report['series'], array('name' => $motivo->nombre, 'data' => $data, 'type' => 'column')
                    );
                }
                break;
            //dias
            case ($dias >= 1 && $dias <= 30):
                $fin->add(new DateInterval('PT23H59M59S'));
                $interval = DateInterval::createFromDateString('1 day');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                foreach ($motivos as $motivo) {
                    $data = array();
                    foreach ($period as $date) {
                        $inicio = $date->format('Y-m-d H:i:s');
                        $categoria = $date->format('d-M');
                        $date->add(new DateInterval('PT23H59M59S'));
                        $fin = $date->format('Y-m-d H:i:s');
                        $report['xAxis']['categories'][] = $categoria;
                        array_push($data, $this->consulta($motivo, $inicio, $fin));
                    }
                    array_push($report['series'], array('name' => $motivo->nombre, 'data' => $data, 'type' => 'column')
                    );
                }
                break;
            //semanas
            case ($dias >= 31 && $dias <= 83):
                if ($inicio->format('D') != 'Mon') {
                    $inicio->modify('last monday');
                }
                if ($fin->format('D') == 'Mon') {
                    $fin->add(new DateInterval('P6DT23H59M59S'));
                }

                $interval = DateInterval::createFromDateString('1 week');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                foreach ($motivos as $motivo) {
                    $data = array();
                    foreach ($period as $date) {
                        $inicio = $date->format('Y-m-d H:i:s');
                        $categoria = $date->format('d/M');
                        $date->add(new DateInterval('P6DT23H59M59S'));
                        $fin = $date->format('Y-m-d H:i:s');
                        $categoria.=' - ' . $date->format('d/M');
                        $report['xAxis']['categories'][] = $categoria;
                        array_push($data, $this->consulta($motivo, $inicio, $fin));
                    }
                    array_push($report['series'], array('name' => $motivo->nombre, 'data' => $data, 'type' => 'column')
                    );
                }
                break;
            //meses
            case ($dias >= 84):
                $interval = DateInterval::createFromDateString('1 month');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                foreach ($motivos as $motivo) {
                    $data = array();
                    foreach ($period as $date) {
                        $date->modify('first day of this month');
                        $inicio = $date->format('Y-m-d H:i:s');
                        $categoria = $date->format('F');
                        $date->modify('last day of this month');
                        $date->add(new DateInterval('PT23H59M59S'));
                        $fin = $date->format('Y-m-d H:i:s');
                        $report['xAxis']['categories'][] = $categoria;
                        array_push($data, $this->consulta($motivo, $inicio, $fin));
                    }
                    array_push($report['series'], array('name' => $motivo->nombre, 'data' => $data, 'type' => 'column')
                    );
                }
                break;
        }
        return $report;
    }

    private function consulta($empleado, $inicio, $fin) {
        $data = array();

        $consulta = Yii::app()->db->createCommand()
                ->select('e.nombre as nombre, count(p.id) as count')
                ->from('pedido p')
                //                ->join('llamada_submotivo sub', 'sub.id = lla.submotivo_id');
                ->join('empleado e', "e.id = p.empleado_id");
        //        if ($motivo_id) {
        //            $consulta->where('sub.estado=:estado and lla.submotivo_id = :motivo and lla.tipo=:tipo and lla.fecha_creacion between :inicio and :fin', array(':estado' => 'ACTIVO', ':motivo' => $motivo->id, ':tipo' => 'ENTRANTE', ':inicio' => $inicio, ':fin' => $fin))
        //                    ->group('sub.id')
        //                    ->order('mot.nombre');
        //        } else 
        {
            $consulta->where('e.id=:empleado_id and p.fecha between :inicio and :fin', array(':empleado_id' => $empleado->id, ':inicio' => $inicio, ':fin' => $fin));
            //                    ->group('mot.id')
            //                    ->order('e.nombre');
        }
        $options = $consulta->queryAll();

        if (!empty($options)) {
            $data[] = (int) $options['0']['count'];
        } else {
            $data[] = (int) '0';
        }

        return $data;
    }

    public function generateColumnReportEmpleados($inicio, $fin) {
        $inicio = DateTime::createFromFormat('d/m/Y', $inicio)->setTime(0, 0, 0);
        $fin = DateTime::createFromFormat('d/m/Y', $fin)->setTime(23, 59, 59);
        $dias = 0;
        $report = array();
        $report['title']['text'] = 'Ventas por empleado';
        $report['credits']['enabled'] = false;
        $report['chart']['height'] = '400';
//        $report['chart']['type'] = 'column';
//		   $report['chart']['margin'] = '75';
//
//		 $report['chart']['options3d'] = array(
//                'enabled'=> true,
//                'alpha'=> 10,
//                'beta'=> 25,
//               
//            );
//			$report['plotOptions']= array('column'=>array(
//                'depth'=> 25
//            ));
        $report['subtitle']['text'] = ' Desde: ' . $inicio->format('d-m-Y') . '  Hasta: ' . $fin->format('d-m-Y');
        $report['xAxis']['labels'] = array("rotation" => 0);
        $report['yAxis']['min'] = 0;
        $report['yAxis']['title']['text'] = "Ventas en Dolares";
        $report['yAxis']['allowDecimals'] = false;
        $report['xAxis']['categories'] = array();
        $report['plotOptions'] = array(
            'series' => array(
                'borderWidth' => 0,
                'dataLabels' => array(
                    'enabled' => true,
                    'format' => '{point.y:.2f}$',
                    'style' => array(
//                        'fontSize' => '15px',
                        'font-weight' => 'bold',
                        'fontFamily' => 'Verdana, sans-serif',
//                        'textShadow' => '0 0 3px black'
                    )
                )
            )
        );

        $report['series'] = array();
        $empleados = Empleado::model()->findall();
        $report['xAxis']['categories'][] = "Ventas";
        $dataLabels = array(
            'enabled' => true,
            'rotation' => 0,
            'color' => 'white',
            'align' => 'right',
            'x' => 3,
            'y' => 0,
            'style' => array(
                'fontSize' => '15px',
                'font-weight' => 'bold',
                'fontFamily' => 'Verdana, sans-serif',
                'textShadow' => '0 0 3px black'
        ));
        foreach ($empleados as $empleado) {
            $data = array();
            $resultado = $this->consultaEmpleado($empleado, $inicio, $fin);
            if ($resultado[0]) {
                array_push($data, $resultado);
                array_push($report['series'], array('name' => $empleado->nombre, 'data' => $data, 'type' => 'column'));
            }
        }
//        array_merge($report['series'], array('dataLabels'=>$dataLabels));

        return $report;
    }

    private function consultaEmpleado($empleado, $inicio, $fin) {

        $data = array();

        $consulta = Yii::app()->db->createCommand()
                ->select('e.nombre as nombre, sum(p.valor_total) as count')
                ->from('pedido p')
                ->join('empleado e', "e.id = p.empleado_id"); {
            $consulta->where('p.estado!="ANULADO" AND e.id=:empleado_id and p.fecha between :inicio and :fin', array(':empleado_id' => $empleado->id, ':inicio' => $inicio->format('Y-m-d H:i:s'), ':fin' => $fin->format('Y-m-d H:i:s')));
        }
        $options = $consulta->queryAll();

        if (!empty($options)) {
            $data[] = (doubleval($options['0']['count']));
        } else {
            $data[] = (int) '0';
        }

        return $data;
    }

    public function generateColumnReportVentas($inicio, $fin) {
        $inicio = DateTime::createFromFormat('d/m/Y', $inicio)->setTime(0, 0, 0);
        $fin = DateTime::createFromFormat('d/m/Y', $fin)->setTime(0, 0, 0);
        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
        $dias = 0;
        $report = array();
        $report['title']['text'] = 'Ventas';
        $report['credits']['enabled'] = false;
        $report['chart']['height'] = '400';
        $report['chart']['type'] = 'column';
        $report['chart']['margin'] = '85';

        $report['chart']['options3d'] = array(
            'enabled' => true,
            'alpha' => 7,
            'beta' => 15,
        );
        $report['plotOptions'] = array('column' => array(
                'depth' => 25
        ));
        $report['subtitle']['text'] = ' Desde: ' . $inicio->format('d-m-Y') . '  Hasta: ' . $fin->format('d-m-Y');
        $report['xAxis']['labels'] = array("rotation" => -45);
        $report['yAxis']['min'] = 0;
        $report['yAxis']['title']['text'] = "Numero de ventas";
        $report['yAxis']['allowDecimals'] = false;
        $report['xAxis']['categories'] = array();
        $report['series'] = array();
        $motivos = Empleado::model()->findall();
        //        array_push($motivos);
        foreach ($period as $date) {
            $dias++;
        }
        switch (true) {
            //horas
            case ($dias == 0):
                $interval = DateInterval::createFromDateString('1 hour');
                $fin->add(new DateInterval('PT23H59M59S'));
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
//                foreach ($motivos as $motivo) {
                $data = array();
                foreach ($period as $date) {

                    $inicio = $date->format('Y-m-d H:i:s');
                    $categoria = $date->format('H:i');
                    $date->add(new DateInterval('PT59M59S'));
                    $fin = $date->format('Y-m-d H:i:s');
                    $report['xAxis']['categories'][] = $categoria;
                    array_push($data, $this->consultaVentas($inicio, $fin));
                }

                array_push($report['series'], array('name' => 'Ventas', 'data' => $data, 'type' => 'column')
                );
//                }
                break;
            //dias
            case ($dias >= 1 && $dias <= 30):
                $fin->add(new DateInterval('PT23H59M59S'));
                $interval = DateInterval::createFromDateString('1 day');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
                //                foreach ($motivos as $motivo) {
                $data = array();
                foreach ($period as $date) {
                    $inicio = $date->format('Y-m-d H:i:s');
                    $categoria = $date->format('d-M');
                    $date->add(new DateInterval('PT23H59M59S'));
                    $fin = $date->format('Y-m-d H:i:s');
                    $report['xAxis']['categories'][] = $categoria;
                    array_push($data, $this->consultaVentas($inicio, $fin));
//                    array_push($report['series'], array('name' => $categoria, 'data' => $data, 'type' => 'column'));
                }
                array_push($report['series'], array('name' => 'Ventas', 'data' => $data, 'type' => 'column'));
                //                }
                break;
            //semanas
            case ($dias >= 31 && $dias <= 83):
                if ($inicio->format('D') != 'Mon') {
                    $inicio->modify('last monday');
                }
                if ($fin->format('D') == 'Mon') {
                    $fin->add(new DateInterval('P6DT23H59M59S'));
                }

                $interval = DateInterval::createFromDateString('1 week');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
//                foreach ($motivos as $motivo) {
                $data = array();
                foreach ($period as $date) {
                    $inicio = $date->format('Y-m-d H:i:s');
                    $categoria = $date->format('d/M');
                    $date->add(new DateInterval('P6DT23H59M59S'));
                    $fin = $date->format('Y-m-d H:i:s');
                    $categoria.=' - ' . $date->format('d/M');
                    $report['xAxis']['categories'][] = $categoria;
                    array_push($data, $this->consultaVentas($inicio, $fin));
                }
                array_push($report['series'], array('name' => 'Ventas', 'data' => $data, 'type' => 'column')
                );
//                }
                break;
            //meses
            case ($dias >= 84):
                $interval = DateInterval::createFromDateString('1 month');
                $period = new DatePeriod($inicio, $interval, $fin); //frecuencia del intervalo a calcular
//                foreach ($motivos as $motivo) {
                $data = array();
                foreach ($period as $date) {
                    $date->modify('first day of this month');
                    $inicio = $date->format('Y-m-d H:i:s');
                    $categoria = $date->format('F');
                    $date->modify('last day of this month');
                    $date->add(new DateInterval('PT23H59M59S'));
                    $fin = $date->format('Y-m-d H:i:s');
                    $report['xAxis']['categories'][] = $categoria;
                    array_push($data, $this->consultaVentas($inicio, $fin));
                }
                array_push($report['series'], array('name' => 'Ventas', 'data' => $data, 'type' => 'column')
                );
//                }
                break;
        }
        return $report;
    }

    private function consultaVentas($inicio, $fin) {

        $data = array();

        $consulta = Yii::app()->db->createCommand()
                ->select(' count(p.id) as count,SUM( p.valor_total ) AS total')
                ->from('pedido p');
//                ->join('empleado e', "e.id = p.empleado_id"); 
        {
            $consulta->where("p.estado != 'ANULADO' AND p.fecha between :inicio and :fin", array(':inicio' => $inicio, ':fin' => $fin));
        }
        $options = $consulta->queryAll();

        if (!empty($options)) {
            $data[] = (int) $options['0']['total'];
        } else {
            $data[] = (int) '0';
        }
        return $data;
    }

    public function generateBar() {
        $data = $this->consultaRankingMenus();
        $report = array();
        $report['chart']['type'] = 'bar';
        $report['chart']['height'] = '320';
//           $report['chart']['type'] = 'column';
//		   $report['chart']['margin'] = '75';
//
//		 $report['chart']['options3d'] = array(
//                'enabled'=> true,
//                'alpha'=> 5,
//                'beta'=> 5,
//               
//            );
//			$report['plotOptions']= array('column'=>array(
//                'depth'=> 25
//            ));
        $report['title']['text'] = '';
        $report['credits']['enabled'] = false;
        $report['xAxis']['categories'] = $data['categorias'];
        $report['yAxis']['title']['text'] = 'Menus';
        $report['yAxis']['title']['align'] = 'high';
        $report['yAxis']['title']['labels']['overflow'] = 'justify';
        $report['yAxis']['min'] = 0;
        $report['colors']['colors'] = array('#FFD148', '#FFD148', '#6AC36A');
//        $report['tooltip']['valueSuffix'] = ' Clientes';
        $report['credits']['enabled'] = false;
        $report['plotOptions']['bar']['dataLabels']['enabled'] = true;
        $report['series'][] = array('name' => 'Menus', 'data' => $data['series']);
        return $report;
    }

    public function generateBarNegativos() {
        $data = $this->consultaRankingMenusNegativos();
        $report = array();
        $report['chart']['type'] = 'bar';
        $report['chart']['height'] = '320';
//           $report['chart']['type'] = 'column';
//		   $report['chart']['margin'] = '75';
//
//		 $report['chart']['options3d'] = array(
//                'enabled'=> true,
//                'alpha'=> 5,
//                'beta'=> 5,
//               
//            );
//			$report['plotOptions']= array('column'=>array(
//                'depth'=> 25
//            ));
        $report['title']['text'] = '';
        $report['credits']['enabled'] = false;
        $report['xAxis']['categories'] = $data['categorias'];
        $report['yAxis']['title']['text'] = 'Menus';
        $report['yAxis']['title']['align'] = 'high';
        $report['yAxis']['title']['labels']['overflow'] = 'justify';
        $report['yAxis']['min'] = 0;
        $report['colors']['colors'] = array('#FFD148', '#FFD148', '#6AC36A');
//        $report['tooltip']['valueSuffix'] = ' Clientes';
        $report['credits']['enabled'] = false;
        $report['plotOptions']['bar']['dataLabels']['enabled'] = true;
        $report['series'][] = array('name' => 'Menus', 'data' => $data['series']);
        return $report;
    }

    private function consultaRankingMenus() {
        $data = array();
        $data['series'] = array();
        $data['categorias'] = array();
        $consulta = Yii::app()->db->createCommand()
                ->select('m.nombre as nombres ,sum(pm.cantidad) menus')
                ->from("pedido_menu pm")
                ->leftJoin('menu m', 'm.id = pm.menu_id')
//                ->where('c.estado=:estado', array(':estado' => Doctor::ESTADO_ACTIVO))
                ->group('pm.menu_id')
                ->order('menus DESC')
                ->limit(5);


        $options = $consulta->queryAll();
        foreach ($options as $key => $value) {
            array_push($data['categorias'], $value['nombres']);
            array_push($data['series'], (int) $value['menus']);
        }

        return $data;
    }

    private function consultaRankingMenusNegativos() {
        $data = array();
        $data['series'] = array();
        $data['categorias'] = array();
        $consulta = Yii::app()->db->createCommand()
                ->select('m.nombre as nombres ,sum(pm.cantidad) menus')
                ->from("pedido_menu pm")
                ->rightJoin('menu m', 'm.id = pm.menu_id')
//                ->where('c.estado=:estado', array(':estado' => Doctor::ESTADO_ACTIVO))
                ->group('m.id')
                ->order('menus ASC')
                ->limit(5);


        $options = $consulta->queryAll();
        foreach ($options as $key => $value) {
            array_push($data['categorias'], $value['nombres']);
            array_push($data['series'], (int) $value['menus']);
        }

        return $data;
    }

}
